package com.jagochan.imchat.module.user.event.listener;

import com.jagochan.imchat.module.user.dao.UserDao;
import com.jagochan.imchat.module.user.domain.entity.User;
import com.jagochan.imchat.module.user.domain.enums.IdempotentEnum;
import com.jagochan.imchat.module.user.domain.enums.ItemEnum;
import com.jagochan.imchat.module.user.domain.enums.ItemTypeEnum;
import com.jagochan.imchat.module.user.event.UserRegisterEvent;
import com.jagochan.imchat.module.user.service.UserBackpackService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

@Component
public class UserRegisterListener {

    @Resource
    private UserBackpackService userBackpackService;

    @Resource
    private UserDao userDao;

    // 在事件发布者事务提交后执行（发放改名卡失败也不会影响注册）
    @TransactionalEventListener(value = UserRegisterEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    // @EventListener(UserRegisterEvent.class)
    public void giveModifyNameCard(UserRegisterEvent event) {
        // 获取用户信息
        User user = event.getUser();

        // 发放改名卡
        userBackpackService.requireItem(user.getId(), ItemEnum.MODIFY_NAME_CARD.getId(), IdempotentEnum.UID, user.getId().toString());
    }

    /**
     * 发放徽章
     *
     * @param event
     */
    @TransactionalEventListener(value = UserRegisterEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    public void giveTag(UserRegisterEvent event) {
        // 获取用户信息
        User user = event.getUser();

        // 当前用户数量
        int count = userDao.count();

        ItemEnum itemEnum; // 要发放的徽章类型
        if (count < 10) {
            itemEnum = ItemEnum.REG_TOP10_BADGE;
        } else if (count < 100) {
            itemEnum = ItemEnum.REG_TOP100_BADGE;
        } else {
            return;
        }

        userBackpackService.requireItem(user.getId(),
                itemEnum.getId(),
                IdempotentEnum.UID,
                user.getId().toString());

    }
}
